import { useState, useEffect } from "react"
import { Form } from 'antd';

import { postJson } from '@/utils/http/linitly.request.js'
import { successPrompt } from '@/utils/default.prompt.js'
import { FIND_BY_ID_URL, INSERT_URL, UPDATE_BY_ID_URL } from '@/constant/common/common'

const useCU = (
  urlInfix,
  name,
  // 数据id，修改时需要
  dataId,
  // 添加/修改方法执行成功的回调
  succCallback,
  findFromStart = true,
) => {

  const [ CUForm ] = Form.useForm()
  const [ confirmLoading, setConfirmLoading ] = useState(false)

  useEffect(() => {
    findFromStart && (dataId && findById())
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [findFromStart, dataId])

  function insert() {
    CUForm.validateFields().then(values => {
      setConfirmLoading(true)
      postJson(urlInfix + INSERT_URL, values).then(() => {
        successPrompt('添加' + name + '成功')
        succCallback()
      }).finally(() => {
        setConfirmLoading(false)
      })
    })
  }

  function update() {
    CUForm.validateFields().then(values => {
      setConfirmLoading(true)
      postJson(urlInfix + UPDATE_BY_ID_URL, {
        ...values,
        id: dataId
      }).then(() => {
        successPrompt('修改' + name + '成功')
        succCallback()
      }).finally(() => {
        setConfirmLoading(false)
      })
    })
  }

  function findById() {
    dataId && postJson(urlInfix + FIND_BY_ID_URL + '/' + dataId).then((res) => {
      CUForm.setFieldsValue(res)
    })
  }

  return [ confirmLoading, CUForm, insert, update, findById ]
}

export default useCU
